<template>
  <div id="app">
    <div class="app-content">
      <div class="app-menu-content" :style="{ width: `${sidebarWidth}px` }">
        <el-menu
          class="app-menu"
          :default-active="activeIndex"
          router
          background-color="#545c64"
          text-color="#fff"
          active-text-color="#ffd04b"
          @select="handleOpen"
          :unique-opened="true"
        >
          <el-menu-item v-for="item in routeList" :index="item.path" :key="item.path">
            {{ item.meta.title }}
          </el-menu-item>
        </el-menu>
      </div>
      <transition name="fade">
        <div class="main-content" :style="{ width: `calc(100% - ${sidebarWidth}px)` }">
          <router-view />
        </div>
      </transition>
    </div>
  </div>
</template>

<script lang="ts">
import { Component, Vue } from 'vue-property-decorator';
import { RouteConfig } from 'vue-router';

@Component({ components: {} })
export default class Layout extends Vue {
  activeIndex = '/';
  routeList: RouteConfig[] = []; // 所有路由信息
  sidebarWidth = 220;

  handleOpen(key: string) {
    this.activeIndex = key;
  }

  // 解决刷新时 高亮错误问题
  setActiveIndex() {
    const route = window.location.hash.slice(1);
    if (this.routeList.find(item => item.path === route)) {
      this.activeIndex = route;
    } else {
      this.activeIndex = '/';
    }
  }

  created() {
    this.routeList = (this.$router.options.routes as RouteConfig[]).filter(item => item.meta?.sidebar === true);
    this.setActiveIndex();
  }
}
</script>

<style lang="scss" scoped>
.app-content {
  height: 100vh;
  width: 100%;
  background: #fff;
  display: flex;

  .app-menu-content {
    box-sizing: border-box;
  }
  .app-menu {
    height: 100vh;
    overflow-y: auto;
  }

  .main-content {
    padding: 16px 16px 0 16px;
    box-sizing: border-box;
  }
}
</style>
